package com.birdboot.core;

import com.birdboot.http.HttpServletRequest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;

/**
 * 该线程的任务是与指定的客户端完成HTTP交互
 * HTTP协议要求一问一答
 * 对此,这里的处理大致分为三步
 * 1:解析请求
 * 2:处理请求
 * 3:发送响应
 */
public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //1解析请求
            //V4:将解析请求改为实例化请求对象
            HttpServletRequest request = new HttpServletRequest(socket);

            //2处理请求
            //测试通过请求对象获取解析出来的请求中的相关信息(获取uri,抽象路径部分)
            String path = request.getUri();
            System.out.println("抽象路径:" + path);

            //定位类加载路径固定写法
            File baseDir = new File(
                    ClientHandler.class.getClassLoader().getResource(".").toURI()
            );
            File staticDir = new File(baseDir, "static");
            File file = new File(staticDir, path);
            /*
            * 将服务器的相应信息发送给浏览器
            * HTTP/1.1 404 NotFound(CRLF)
Content-Type: text/html(CRLF)
Content-Length: 2546(CRLF)(CRLF)
1011101010101010101......
            * */

            //3发送响应
            // 1:用File对象定位index.html
            /*
             * 实际开发中常用的相对路径是:类加载路径
             * 对应位置就是当前项目中仍和一个java定义的包中最上层包的父目录
             * 举例:
             * 当前类ClientHandler
             * */
            //1发送状态行
            println("HTTP/1.1 200 OK");
            //2发送响应头
            println("Content-Type: text/html");
            println("Content-Length: " + file.length());
            //单独发送回车加换行
            println("");

            //3发送响应正文(index.html页面内容发送出去)
            OutputStream os = socket.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            byte[] data = new byte[1024 * 10];
            int len;
            while ((len = fis.read(data)) != -1) {
                os.write(data, 0, len);
            }
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        } finally {
            //遵循HTTP协议要求,一问一答后与客户端断开连接
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void println(String line) throws IOException {
        OutputStream os = socket.getOutputStream();
        //1发送状态行
        os.write(line.getBytes(StandardCharsets.ISO_8859_1));
        os.write(13);//单独发送回车符
        os.write(10);//单独发送换行符
    }


}
